const { getUserId } = require('../../utils')

const isAuthor = async (ctx, id, userId) => {
  const exist = await ctx.db.exists.Comment({ id, author: { id: userId } })
  if (!exist) {
    throw new Error('need comment author')
  }
}

const comment = {
  async createComment (parent, { content, partId, replyIds }, ctx, info) {
    const userId = getUserId(ctx)
    const articles = await ctx.db.query.articles({
      where: {
        AND: [{
          parts_some: {
            id: partId
          }
        }, {
          OR: [{
            owner: {
              id: userId
            }
          },
          {
            cooperations_some: {
              user: {
                id: userId
              }
            }
          }, {
            share: 'PUBLIC'
          }]
        }]
      }
    })
    if (!articles || articles.length <= 0) {
      throw new Error('you can not find the article')
    }
    const replies = {}
    if (replyIds && replyIds.length > 0) {
      replies.connect = replyIds
    }
    return ctx.db.mutation.createComment({
      data: {
        content,
        author: {
          connect: {
            id: userId
          }
        },
        replies,
        part: {
          connect: {
            id: partId
          }
        }
      }
    }, info)
  },
  async deleteComment (parent, { id }, ctx, info) {
    const userId = getUserId(ctx)
    // 先判断是否有操作权限
    await isAuthor(ctx, id, userId)
    return ctx.db.mutation.deleteComment({
      where: {
        id
      }
    }, info)
  }
}

module.exports = { comment }
